var app = getApp();
var WxParse = require('../../lib/wxParse/wxParse.js');
var util = require('../../utils/util.js');
var api = require('../../config/api.js');
const draw = require('../../utils/common/drawhaibao.js');

var lastTime = null;

Page({
  data: {
    id: '',
    goods: {},
    lunbotu: [],
    canshu: [],
    dggList: [],
    tuijianGoods: [],
    cartGoodsCount: 0,
    usershoucang: 0,
    number: 1,
    dggchoose: '规格数量选择',
    ggname: '请选择规格数量',
    dgggoodsid: '',
    dggxiaoshoujia: 0,
    opendgg: false,
    openShare: false,
    openTwocodeimg: false,
    shareImage: '',
    canWrite: false, //用户是否获取了保存相册的权限
    fukucunsale: true, //true为允许负库存销售；false为不允许
    shouqing: false,
    webstore: '',
    template: {},
    image: "",
    zhutu: "",
    twoCodeUrl: "",
    shareUserId: '',
    page: 1,
    limit: 10
  },

  // 获取商品信息
  getGoodsInfo: function () {
    let that = this;
    util.request(api.GoodsDetail, {
      id: that.data.id
    }).then(function (res) {
      if (res) {
        if (res.result == 1) {
          var _canshu = [];
          var _lunbotu = [];
          if (res.data.goods.canshuList.length > 0) {
            _canshu = JSON.parse(res.data.goods.canshuList);
          }
          if (res.data.goods.lunbotu.length > 0) {
            _lunbotu = JSON.parse(res.data.goods.lunbotu);
          }
          that.setData({
            goods: res.data.goods,
            fukucunsale: res.data.fukucunsale,
            dggList: res.data.dggGoodsDtoList,
            lunbotu: _lunbotu,
            canshu: _canshu,
            dggxiaoshoujia: res.data.goods.xiaoshoujia,
            ggname: res.data.goods.ggname,
            usershoucang: res.data.usershoucang,
            dgggoodsid: res.data.dgggoodsid
          });
          //初始化默认多规格为标准
          let _dggList = res.data.dggGoodsDtoList;
          for (let i = 0; i < _dggList.length; i++) {
            if (_dggList[i].id == res.data.dgggoodsid) {
              _dggList[i].checked = true;
            } else {
              _dggList[i].checked = false;
            }
          }
          that.setData({
            dggList: _dggList,
          });
          //判断是否售罄
          if (res.data.goods.kucun <= 0) {
            that.setData({
              shouqing: true
            });
          }
          WxParse.wxParse('goodsDetail', 'html', res.data.goods.xiangxijieshao, that);
          //显示购物车数量
          that.getcartgoodnum();
          //获取推荐商品
          that.getGoodsTuijian();
        }
      }
    });
  },

  //显示购物车数量
  getcartgoodnum: function () {
    let that = this;
    var cartnum = wx.getStorageSync('cartnum');
    that.setData({
      cartGoodsCount: cartnum
    });
  },

  // 获取推荐商品
  getGoodsTuijian: function () {
    let that = this;
    util.request(api.GoodsTuijian, {
      "id": that.data.id,
      "page": that.data.page,
      "limit": that.data.limit
    }).then(function (res) {
      if (res.result == 1) {
        if (res.data.length > 0) {
          that.setData({
            tuijianGoods: that.data.tuijianGoods.concat(res.data),
            page: that.data.page + 1
          });
        } else {
          wx.showToast({
            title: '已经被您看完了!',
            icon: 'none',
            duration: 2000
          });
          return false;
        }
      }
    });
  },

  // 规格选择
  choosedgg: function (event) {
    let that = this;
    let dggId = event.currentTarget.dataset.valueId;
    //判断是否可以点击

    //TODO 性能优化，可在wx:for中添加index，可以直接获取点击的属性名和属性值，不用循环
    let _dggList = this.data.dggList;
    for (let i = 0; i < _dggList.length; i++) {
      if (_dggList[i].id == dggId) {
        //如果已经选中，则反选
        if (_dggList[i].checked) {
          _dggList[i].checked = false;
        } else {
          _dggList[i].checked = true;
          //选择了，则判断当前是否有图片，且图片内容不能为空，不能为默认lazy图片，则替换
          that.setdggzhutu(_dggList[i].dggzhutu);
        }
      } else {
        _dggList[i].checked = false;
      }
    }
    this.setData({
      dggList: _dggList,
    });
    //重新计算spec改变后的信息
    this.choosedgginfo();

    //重新计算哪些值不可以点击
  },

  setdggzhutu: function (dggzhu) {
    if (dggzhu && dggzhu.length > 1 && dggzhu.indexOf("lazyload.png") == -1)
      this.setData({
        dggzhutu: dggzhu,
      });
  },

  //获取选中的规格信息
  getchoosedggValue: function () {
    let dggvalues = [];
    let _dggList = this.data.dggList;
    for (let i = 0; i < _dggList.length; i++) {
      let _checkedObj = {
        id: 0,
        dggname: '',
        dggxiaoshoujia: 0,
        dggkucun: 0
      };
      if (_dggList[i].checked) {
        _checkedObj.id = _dggList[i].id;
        _checkedObj.dggname = _dggList[i].dggname;
        _checkedObj.dggxiaoshoujia = _dggList[i].dggxiaoshoujia;
        _checkedObj.dggkucun = _dggList[i].dggkucun;
      }
      dggvalues.push(_checkedObj);
    }
    return dggvalues;
  },

  // 规格改变时，重新计算价格及显示信息
  choosedgginfo: function () {
    let checkedNameValue = this.getchoosedggValue();
    //设置选择的信息
    let checkedValue = checkedNameValue.filter(function (v) {
      if (v.id != 0) {
        return true;
      } else {
        return false;
      }
    }).map(function (v) {
      return v;
    });
    if (checkedValue.length > 0) {
      this.setData({
        dgggoodsid: checkedValue[0].id,
        ggname: checkedValue[0].dggname,
        dggxiaoshoujia: checkedValue[0].dggxiaoshoujia
      });
      if (checkedValue[0].dggkucun <= 0) {
        this.setData({
          shouqing: true
        })
      } else {
        this.setData({
          shouqing: false
        })
      }
    } else {
      this.setData({
        ggname: '请选择规格数量'
      });
    }

  },

  //添加或是取消收藏
  addshoucangOrNot: function () {
    let that = this;
    if (!app.globalData.hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    }
    util.request(api.ShouCangAddOrDelete, {
        type: that.data.usershoucang,
        goodsid: this.data.id
      }, "POST")
      .then(function (res) {
        if (res.result == 1) {
          if (res.data.type == 0) {
            that.setData({
              usershoucang: 1
            });
          } else {
            that.setData({
              usershoucang: 0
            });
          }
        } else {
          wx.showToast({
            image: '/static/images/icon_error.png',
            title: _res.errmsg,
            mask: true
          });
        }
      });
  },

  //立即购买（先自动加入购物车）
  buyadd: function () {
    var that = this;
    let nowTime = +new Date();
    if (nowTime - lastTime > 500 || !lastTime) { //5秒内避免重复提交订单
      lastTime = nowTime;
    } else {
      return false;
    }
    if (this.data.opendgg == false) {
      //打开规格选择窗口
      this.setData({
        opendgg: !this.data.opendgg
      });
    } else {
      //立即购买
      util.request(api.ShoppingCartBuyAdd, {
          number: this.data.number,
          goodsid: that.data.dgggoodsid
        }, "POST")
        .then(function (res) {
          if (res.result == 1) {
            that.setData({
              opendgg: !that.data.opendgg
            });
            // 如果storage中设置了cartId，则是立即购买，否则是购物车购买
            wx.setStorageSync('shoppingcartid', res.data.shoppingcartid);
            wx.navigateTo({
              url: '/pages/order/order'
            })
          } else {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: res.errmsg,
              mask: true
            });
          }
        });
    }
  },

  //添加到购物车
  addToCart: function () {
    var that = this;
    if (this.data.opendgg == false) {
      //打开规格选择窗口
      this.setData({
        opendgg: !this.data.opendgg
      });
    } else {
      //添加到购物车
      util.request(api.ShoppingCartAdd, {
          number: this.data.number,
          goodsid: that.data.dgggoodsid
        }, "POST")
        .then(function (res) {
          if (res.result == 1) {
            wx.showToast({
              title: '添加成功'
            });
            that.setData({
              opendgg: !that.data.opendgg
            });
            //判断是否已经添加过购物车，如果没有则+1
            if (res.data == "add") {
              var _cartnum = parseInt(that.data.cartGoodsCount) + 1
              that.setData({
                cartGoodsCount: _cartnum
              });
              wx.setStorageSync('cartnum', _cartnum);
            }
          } else {
            wx.showToast({
              image: '/static/images/icon_error.png',
              title: _res.errmsg,
              mask: true
            });
          }
        });
    }
  },

  cutNumber: function () {
    this.setData({
      number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
    });
  },

  addNumber: function () {
    this.setData({
      number: this.data.number + 1
    });
  },

  switchdgg: function () {
    if (this.data.opendgg == false) {
      this.setData({
        opendgg: !this.data.opendgg
      });
    }
  },

  closedgg: function () {
    this.setData({
      opendgg: false,
    });
  },


  openCartPage: function () {
    wx.switchTab({
      url: '/pages/shoppingcart/shoppingcart'
    });
  },

  // 页面分享
  onShareAppMessage: function () {
    let that = this;
    let memberUserid = wx.getStorageSync('memberUserid');
    return {
      title: that.data.goods.goodsname,
      desc: '好东西要一起分享！',
      path: '/pages/goods/goods?id=' + that.data.id + '&shareMemberUserid=' + memberUserid
    }
  },

  shareFriendOrCircle: function () {
    let that = this;
    if (that.data.openShare === false) {
      this.setData({
        openShare: !this.data.openShare
      });
    } else {
      return false;
    }
  },

  handleSetting: function (e) {
    var that = this;
    if (!e.detail.authSetting['scope.writePhotosAlbum']) {
      wx.showModal({
        title: '警告',
        content: '不授权无法保存',
        showCancel: false
      })
      that.setData({
        canWrite: false
      })
    } else {
      wx.showToast({
        title: '保存成功'
      })
      that.setData({
        canWrite: true
      })
    }
  },

  closeShare: function () {
    this.setData({
      openShare: false,
    });
    wx.hideLoading()
  },

  closetwocodeimg: function () {
    this.setData({
      openTwocodeimg: false,
    });
    wx.hideLoading()
  },

  // 生成成功
  canvasSuc(e) {
    wx.hideLoading()
    this.setData({
      image: e.detail.path
    })
  },

  // 点击保存海报弹出展示海报图片窗口
  getSave() {
    let that = this;
    that.setData({
      openShare: false
    });
    wx.showLoading({
      title: '正在努力生成中',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 1000);
    var scene = {
      "page": "goods",
      "page_data_id": that.data.id
    };
    util.request(api.CreateQcodeImg, {
      scene: JSON.stringify(scene)
    }, 'GET').then(function (res) {
      that.setData({
        twoCodeUrl: res.data
      });
      wx.getSetting({
        success: function (res) {
          //不存在相册授权
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: function () {
                var drawtemplate = draw.getDraw(that.data.goods.zhutu, that.data.goods.xiaoshoujia, that.data.goods.goodsname, that.data.twoCodeUrl);
                that.setData({
                  canWrite: true,
                  template: drawtemplate
                })
              },
              fail: function (err) {
                // 授权失败
                wx.showModal({
                  title: '警告',
                  content: '您点击了拒绝授权,将无法正常保存图片,点击确定重新获取授权。',
                  success: function (res) {
                    if (res.confirm) {
                      wx.openSetting({
                        success: (res) => {
                          console.log('授权成功')
                        }
                      })
                    }
                  }
                })
              }
            })
          } else {
            var drawtemplate = draw.getDraw(that.data.goods.zhutu, that.data.goods.xiaoshoujia, that.data.goods.goodsname, that.data.twoCodeUrl);
            that.setData({
              canWrite: true,
              openTwocodeimg: true,
              template: drawtemplate
            });
          }
        }
      })
    });
  },

  //保存海报
  savehaibao: function () {
    let that = this;
    wx.getSetting({
      success: (set) => {
        wx.saveImageToPhotosAlbum({
          filePath: that.data.image,
          success: (res) => {
            if (res.errMsg == "saveImageToPhotosAlbum:ok") {
              wx.showModal({
                title: '存图成功',
                content: '图片成功保存到相册了，可以分享到朋友圈了',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#a78845',
                success: function (res) {
                  if (res.confirm) {}
                }
              })
            }
          }
        })
        if (set.authSetting['scope.writePhotosAlbum'] == false) {
          wx.openSetting()
        }
      }
    })
  },
  //预览图片
  previewImg() {
    wx.previewImage({
      current: this.data.image,
      urls: [this.data.image]
    })
  },

  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },

  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    let that = this;
    if (options.id) {
      that.setData({
        id: parseInt(options.id)
      });
    }
    if (options.shareMemberUserid) {
      //这个shareMemberUserid的存在证明是通过分享页面进来的
      util.request(api.Yemianfenxiang, {
        shareMemberUserid: options.shareMemberUserid,
        page_data_id: options.id,
        page: 'goods'
      }, 'GET').then(function (res) {
        if (res.result == 1) {
          console.log(options.shareMemberUserid);
        }
      });
    }
  },
  onShow: function () {
    // 页面显示
    var that = this;
    if (Object.keys(that.data.goods).length == 0) {
      that.getGoodsInfo();
    }
  },

  // 下拉刷新
  onReachBottom() {
    let that = this;
    wx.showNavigationBarLoading() //在标题栏中显示加载
    if (that.data.tuijianGoods.length > 0) {
      that.getGoodsTuijian();
    }
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  //根据已选的值，计算其它值的状态
  setSpecValueStatus: function () {

  },

})